package com.personnel_management.dao;

import com.personnel_management.pojo.Depart;
import com.personnel_management.pojo.Staff;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface DepartDao {
    //添加部门 INSERT INTO depart(name,city) VALUES("营销部","北京");
    @Insert("INSERT INTO depart (name,city) VALUES (#{name},#{city})")
    //@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
    public Integer addDepart(Depart depart);
    //删除部门(根据id) DELETE FROM depart WHERE id=1;
    @Delete("DELETE FROM depart WHERE id=#{id}")
    public Integer deleteDepart(Integer id);
    //修改部门(城市、部门名称)
    @UpdateProvider(type = SetDepart.class,method = "getSql")
    public Integer setDepart(Depart depart);
    //查询部门(按照id) SELECT * FROM depart WHERE id=2;
    @Select("SELECT * FROM depart WHERE id=#{id}")
    public Depart seleteOne(Integer id);
    //查询部门(所有的,根据城市或者部门,或者城市和部门) SELECT * FROM depart;
    @SelectProvider(type = FindDeparts.class,method = "getSql")
    public List<Depart> selectDeparts(Depart depart);
    //查询该部门的员工(根据id) SELECT * FROM staff WHERE depart_id=?
    @Select("SELECT * FROM staff WHERE depart_id=#{id}")
    public List<Staff> selectStaffs(int id);
    //修改部门SQL的内部类
    class SetDepart{
        public String getSql(Depart depart)
        {
            StringBuilder SQL=new StringBuilder("UPDATE depart SET");
            if(depart.getCity()!=null&&depart.getName()==null)
            {
              SQL.append(" city=#{city}");
            }
            else if(depart.getName()!=null&&depart.getCity()==null)
            {
                SQL.append(" name=#{name}");
            }
            //(depart.getName()!=null&&depart.getCity()!=null)
            else
            {
                SQL.append(" city=#{city} ,  name=#{name} ");
            }
            SQL.append(" WHERE id=#{id}");
            return SQL.toString();
        }
    }
    //查找部门SQL的内部类
    class FindDeparts{
        public String getSql(Depart depart)
        {
            StringBuilder SQL=new StringBuilder("SELECT * FROM depart WHERE 1=1");
            if(depart.getCity()!=null)
                SQL.append(" AND city=#{city}");
            if(depart.getName()!=null)
                SQL.append(" AND name=#{name}");
            return SQL.toString();
        }
    }


}
